<template>
  <div class="request-party-service-manage">
    <div class="app-container">
      <div class="mainbox">
        <Header :header-name="$route.meta.title" />

        <div class="request-party-service-manage-body">

          <!-- 搜索板块 -->
          <el-form ref="form" :model="form" inline label-width="80px" class="search-form">
            <el-form-item prop="serviceName">
              <el-input v-model="form.serviceName" clearable :maxlength="100" placeholder="请输入服务名称" />
            </el-form-item>

            <el-form-item prop="sts">
              <el-select v-model="form.sts" clearable placeholder="请选择启用状态">
                <el-option
                  v-for="(item, index) in dictOptions.sts"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item class="query-action">
              <el-button type="primary" :loading="loading" :disabled="loading" @click="searchBtn"> 查询 </el-button>
              <el-button :loading="loading" :disabled="loading" @click="resetBtn"> 重置 </el-button>
              <el-button v-permission="['REQUESTPARTYSERVICEMANAGE_ADD', 'PROVIDERSERVICEMANAGE_ADD']" type="primary" @click="addBtn"> 新增 </el-button>
              <el-button v-permission="['REQUESTPARTYSERVICEMANAGE_DEL', 'PROVIDERSERVICEMANAGE_DEL']" type="danger" :disabled="multipleSelection.length === 0" @click="delBtn()"> 删除 </el-button>
              <el-button v-if="manageType === 2" v-permission="['REQUESTPARTYSERVICEMANAGE_PUBLIC']" type="danger" :disabled="multipleSelection.length === 0" @click="publicBtn()"> 发布 </el-button>
              <el-button type="primary" @click="changeView"> 切换视图 </el-button>
            </el-form-item>
          </el-form>

          <!-- 表格数据视图 -->
          <div v-if="!showTreeView">
            <FlexTable
              v-loading="loading"
              border
              :data="tableData"
              :columns="columnsOptions"
              @selection-change="handleSelectionChange"
            />

            <el-pagination
              :page-size="pagination.pageSize"
              :current-page.sync="pagination.pageNo"
              layout="prev, pager, next, jumper"
              :total="pagination.totalPage"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>

          <!-- 树列表视图 -->
          <el-tree
            v-else
            v-loading="treeLoading"
            style="width: 700px"
            :data="treeData"
            :props="defaultProps"
            :default-expand-all="true"
            :expand-on-click-node="false"
          >
            <p slot-scope="{ node, data }" class="custom-tree-node">
              <span :title="node.label"> <i :class="data.type === 'service' ? 'el-icon-menu' : 'el-icon-s-tools'" /> {{ data.type === 'service' || data.type === 'serviceBefore' ? data.serviceName : node.label }}</span>
              <span class="tree-btn">
                <el-tag v-if="data.type === 'serviceBefore'"> 前置 </el-tag>
                <el-button v-if="data.type === 'service' && ((data.upStatus == '0' || data.upStatus == '3') && manageType === 2 && data.sts == '1')" v-permission="['REQUESTPARTYSERVICEMANAGE_PUBLIC']" type="text" @click="publicBtn(data)"> 发布 </el-button>
                <el-button v-if="data.type === 'service'" v-permission="['REQUESTPARTYSERVICEMANAGE_UPDATE', 'PROVIDERSERVICEMANAGE_UPDATE']" :disabled="(data.upStatus == 1 && manageType === 2) || data.sts == '1'" type="text" @click="updateBtn(data,false)"> 修改 </el-button>
                <el-button v-if="data.type === 'service'" v-permission="['REQUESTPARTYSERVICEMANAGE_DEL', 'PROVIDERSERVICEMANAGE_DEL']" :disabled="(data.upStatus == 1 && manageType === 2) || data.sts == '1'" type="text" class="text-del-btn" @click="delBtn(data)"> 删除 </el-button>
                <el-button v-if="data.type === 'service'" v-permission="['REQUESTPARTYSERVICEMANAGE_FIELD_MAINTENANCE', 'PROVIDERSERVICEMANAGE_FIELD_MAINTENANCE']" :disabled="(data.upStatus == 1 && manageType === 2) || data.sts == '1'" type="text" @click="fieldMaintenanceBtn(data)"> 字段维护</el-button>
                <el-button v-if="data.type === 'service' && manageType === 2" v-permission="['PROVIDERSERVICEMANAGE_PRE_DOWNLINE']" type="text" @click="preDownlineBtn(data)"> 预下线通知 </el-button>
                <el-switch
                  v-if="data.type === 'service'"
                  v-model="data.sts"
                  :disabled="data.upStatus == 1"
                  active-text="已启用"
                  active-value="1"
                  active-color="#87D068"
                  inactive-text="已禁用"
                  inactive-value="2"
                  inactive-color="#D9001B"
                  @change="(val) => switchChange(val, data)"
                />
              </span>
            </p>
          </el-tree>

        </div>

        <!-- 新增/修改服务 -->
        <create-service ref="createService" :manage-type="manageType" @interfaceServiceRefresh="searchBtn" />

        <!-- 字段维护 -->
        <field-maintenance ref="fieldMaintenance" :service-manager-data="serviceManagerData" />

        <!-- 加解密配置 -->
        <EncryptDecrypt ref="encryptDecrypt" @encryptDecryptRefresh="searchBtn" />

        <!-- 预下线通知弹框 -->
        <el-dialog
          title="预下线通知"
          :visible.sync="preDownlineDialogVisible"
          width="600px"
        >
          <el-form ref="preDownlineForm" :model="preDownlineForm" :rules="preDownlineFormRules" label-width="100px">
            <el-form-item label="下线时间:" prop="disableTime">
              <el-date-picker
                v-model="preDownlineForm.disableTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              />
            </el-form-item>
            <el-form-item label="通知方式:" prop="alarmTypes">
              <el-checkbox-group v-model="preDownlineForm.alarmTypes">
                <el-checkbox
                  v-for="(item, index) in dictOptions.notificationMode"
                  :key="index"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="preDownlineDialogVisible = false">取 消</el-button>
            <el-button type="primary" :disabled="!canClick" :loading="!canClick" @click="preDownlineConfirm('preDownlineForm')">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import CreateService from './components/CreateService'
import FieldMaintenance from './components/FieldMaintenance'
import EncryptDecrypt from './components/EncryptDecrypt'
import { pageApi, deleteApi, isUsedApi, updateStsApi,
  getSystemTreeApi, updateUpStatusApi, preOfflineApi } from '@/api/serviceManage/requestPartyServiceManage'
import dictMixin from '@/utils/mixins/dict'
export default {
  name: 'RequestPartyServiceManage',

  components: {
    CreateService,
    FieldMaintenance,
    EncryptDecrypt
  },

  mixins: [
    dictMixin(['sts@Local', 'interface_type', 'interfaceUpStatus', 'notificationMode@Local'])
  ],

  props: {
    // 服务管理分类 1-请求方服务、2-提供方服务
    manageType: {
      type: Number,
      default: 1
    }
  },

  data () {
    return {
      treeLoading: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'systemName'
      },
      showTreeView: false,
      loading: false,
      tableData: [],
      columnsOptions: [
        { type: 'selection' },
        { label: '服务名称', prop: 'serviceName',
         // 点击服务名称跳转到服务详情页
          customRender: (scope) => {
          // 超链接样式
            return <span class="text-link" onClick={() => this.updateBtn(scope.row, true)} >{scope.row.serviceName}</span>
          }
        },
        { label: '关联系统', prop: 'systemName' },
        { label: '服务编号', prop: 'serviceCode' },
        { label: '接口方式',
          customRender: scope => {
            return this.getDictText('interface_type', scope.row.interfaceType)
          }
        },
        { label: '发布状态',
          notShow: this.manageType,
          customRender: scope => {
            return this.getDictText('interfaceUpStatus', scope.row.upStatus)
          }
        },
        { label: '启用状态', width: 200,
          customRender: (scope) => {
            return <el-switch
              disabled={scope.row.upStatus == 1}
              vModel={scope.row.sts}
              active-text='已启用'
              active-value='1'
              active-color='#87D068'
              inactive-text='已禁用'
              inactive-value='2'
              inactive-color='#D9001B'
              onChange={(val) => this.switchChange(val, scope.row)}
            />
          }
        },
        { label: '操作', width: 300, fixed: 'right',
          customRender: (scope) => {
            return [
              /* 请求方服务管理，只根据启禁用状态判断是否可操作按钮，禁用可操作，启用不可操作。
              提供方服务管理，待审核状态下均不可操作，其他状态下根据启禁用状态判断。
              状态： 草稿 1
                    待审核 2
                    已发布 3
                    已拒绝 4 */
              (scope.row.upStatus == '0' || scope.row.upStatus == '3') &&
              this.manageType === 2 && scope.row.sts == '1' && <el-button vPermission={['REQUESTPARTYSERVICEMANAGE_PUBLIC']} type='text' onClick={() => this.publicBtn(scope.row)}> 发布 </el-button>,
              <el-button disabled={(scope.row.upStatus == 1 && this.manageType === 2) || scope.row.sts == '1'} vPermission={['REQUESTPARTYSERVICEMANAGE_UPDATE', 'PROVIDERSERVICEMANAGE_UPDATE']} type='text' onClick={() => this.updateBtn(scope.row,false)}> 修改 </el-button>,
              <el-button disabled={(scope.row.upStatus == 1 && this.manageType === 2) || scope.row.sts == '1'} vPermission={['REQUESTPARTYSERVICEMANAGE_DEL', 'PROVIDERSERVICEMANAGE_DEL']} type='text' class='text-del-btn' onClick={() => this.delBtn(scope.row)}> 删除 </el-button>,
              <el-button disabled={(scope.row.upStatus == 1 && this.manageType === 2) || scope.row.sts == '1'} vPermission={['REQUESTPARTYSERVICEMANAGE_FIELD_MAINTENANCE', 'PROVIDERSERVICEMANAGE_FIELD_MAINTENANCE']} type='text' onClick={() => this.fieldMaintenanceBtn(scope.row)}> 字段维护 </el-button>,
              this.manageType === 2 && <el-button vPermission={['PROVIDERSERVICEMANAGE_PRE_DOWNLINE']} type='text' onClick={() => this.preDownlineBtn(scope.row)}> 预下线通知 </el-button>
              // <el-button type='text' onClick={() => this.EAndDBtn(scope.row)}> 加解密配置 </el-button>
            ]
          }
        }
      ],
      form: {
        serviceName: '',
        sts: ''
      },
      // 分页相关
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalPage: 0
      },
      // 表格选中数据
      multipleSelection: [],
      // 服务相关信息传递到子组件
      serviceManagerData: {},
      // 预下线通知弹框
      preDownlineDialogVisible: false,
      preDownlineForm: {
        disableTime: '',
        alarmTypes: []
      },
      preDownlineFormRules: {
        disableTime: { required: true, message: '请选择下线时间', trigger: 'change' },
        alarmTypes: { required: true, message: '请选择通知方式', trigger: 'change' }
      },
      serviceId: '',
      canClick: true
    }
  },

  created () {
    this.getTableData()
  },

  methods: {
    // 启用/禁用
    switchChange (val, row) {
      const changeSts = () => {
        updateStsApi({
          id: row.id,
          manageType: this.manageType,
          sts: val
        }).then(({ code, data }) => {
        }).finally(() => {
          this.searchBtn()
        })
      }

      if (val == 2) {
        // 禁用
        isUsedApi({
          id: row.id
        }).then(({ code, data }) => {
          if (data) {
            this.$confirm('当前服务已经被使用, 是否继续禁用?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              changeSts()
            }).catch(() => {
              this.searchBtn()
            })
          } else {
            changeSts()
          }
        })
      } else {
        // 启用
        changeSts()
      }
    },

    // 表格选中数据
    handleSelectionChange (val) {
      this.multipleSelection = val
    },

    // 获取表格数据
    getTableData () {
      this.loading = true
      pageApi({
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize,
        manageType: this.manageType,
        ...this.form
      }).then(({ code, data }) => {
        if (code === '00000') {
          this.tableData = data.rows
          this.pagination.totalPage = data.totalRows
        }
      }).finally(() => {
        this.loading = false
      })
    },

    // 获取表格树列表
    getTreeTableData () {
      this.treeLoading = true
      getSystemTreeApi({
        manageType: this.manageType,
        ...this.form
      }).then(({ code, data }) => {
        if (code === '00000') {
          this.treeData = data
        }
      }).finally(() => {
        this.treeLoading = false
      })
    },

    // 修改按钮
    updateBtn (row, isDetail) {
      this.$refs.createService.dialogVisible = true
      this.$refs.createService.getInitData(row, isDetail)
    },

    // 删除按钮
    delBtn (row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteApi({
          ids: row ? row.id.split(',') : this.multipleSelection.map(item => item.id)
        }).then(({ code, data }) => {
          if (code === '00000') {
            this.$message.success('删除成功')
            this.searchBtn()
          }
        })
      })
    },

    // 发布按钮
    publicBtn (row) {
      if (!row && !this.multipleSelection.every(item => item.upStatus == 0)) {
        return this.$message.warning('请选择草稿数据发布')
      }
      this.$confirm('确定发布?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateUpStatusApi({
          ids: row ? row.id.split(',') : this.multipleSelection.map(item => item.id),
          upStatus: 1
        }).then(({ code, data }) => {
          if (code === '00000') {
            this.$message.success('发布成功')
            this.searchBtn()
          }
        })
      })
    },

    // 字段维护按钮
    async fieldMaintenanceBtn (row) {
      this.serviceManagerData = {
        id: row.id,
        serviceName: row.serviceName,
        serviceCode: row.serviceCode,
        topIsList: row.topIsList
      }
      await this.$nextTick()
      this.$refs.fieldMaintenance.initData()
    },

    // 预下线通知按钮
    async preDownlineBtn (row) {
      this.serviceId = row.id
      this.preDownlineDialogVisible = true
      if (row.disableTime) {
        const params = {
          disableTime: row.disableTime,
          alarmTypes: row.alarmTypes
        }
        this.preDownlineForm = this.$arrayStrInterchange(params, ['alarmTypes'])
      } else {
        this.preDownlineForm = {
          disableTime: '',
          alarmTypes: []
        }

        await this.$nextTick()
        this.$refs.preDownlineForm.clearValidate()
      }
    },

    // 预下线通知确定
    preDownlineConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.canClick = false
          const params = this.$arrayStrInterchange(this.preDownlineForm, ['alarmTypes'])
          preOfflineApi({
            serviceId: this.serviceId,
            ...params
          })
            .then(({ code, data }) => {
              if (code === '00000') {
                this.preDownlineDialogVisible = false
                this.$message.success('设置成功')
                this.getTableData()
              }
            }).finally(() => {
              this.canClick = true
            })
        }
      })
    },

    // 加解密配置按钮
    EAndDBtn (row) {
      this.$refs.encryptDecrypt.getInitData(row)
    },

    // 切换视图
    changeView () {
      this.showTreeView = !this.showTreeView

      this.searchBtn()
    },

    // 新增按钮
    async addBtn () {
      this.$refs.createService.dialogVisible = true
      await this.$nextTick()
      this.$refs.createService.getInitData()
    },

    // 搜索按钮
    searchBtn () {
      if (this.showTreeView) this.getTreeTableData()
      else this.getTableData()
    },

    // 重置按钮
    resetBtn () {
      this.$refs.form.resetFields()
      this.searchBtn()
    },

    // 分页操作
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.getTableData()
    },
    handleCurrentChange (val) {
      this.pagination.pageNo = val
      this.getTableData()
    }
  }
}
</script>

<style lang="scss" scoped>
  .request-party-service-manage {
    background: #F2F2F2;

    &-body {
      background: #fff;
      margin-top: 10px;
      padding: 20px;
      height: calc(100vh - 254px);
      overflow-y: auto;
    }
    .el-pagination {
      text-align: right;
      margin-top: 20px;
    }
    .text-link {
      color: #409EFF;
      cursor: pointer;
    }

    .el-tree {
      ::v-deep .el-tree-node__expand-icon {
        font-size: 18px;
      }
      .custom-tree-node {
        width: calc(100% - 30px);
        display: flex;
        align-items: center;
        padding-right: 20px;

        > span:first-child {
          display: inline-block;
          width: calc(100% - 50px);
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          line-height: 40px;
        }

        .tree-btn {
          .el-switch {
            margin-top: -4px;
            margin-left: 10px;
          }
        }
      }
    }
  }
</style>
